<template>
	<div class="container">
		<query-builder v-model="query" @update:modelValue="handleChange">
			<template #default="{scope}">
				<el-cascader :options="options" placeholder="请选择" @change="handleCascaderChange($event, scope)"
					size="small" style="width: 120px; margin-right: 10px"></el-cascader>
				<el-select v-model="scope.operator" size="small" style="width: 100px; margin-right: 10px">
					<el-option label="等于" value="equal" />
					<el-option label="不等于" value="notEqual" />
				</el-select>
				<el-input v-model="scope.value" placeholder="Value" size="small"
					style="width: 200px; margin-right: 10px" />
			</template>
		</query-builder>
		<pre class="output">{{ formattedQuery }}</pre>
	</div>
</template>

<script>
	import QueryBuilder from './QueryBuilder.vue'

	export default {
		components: {
			QueryBuilder
		},
		data() {
			return {
				options: [{
						value: 'js',
						label: '江苏省',
						children: [{
								value: 'nj',
								label: '南京市'
							},
							{
								value: 'sz',
								label: '苏州市'
							},
							{
								value: 'wx',
								label: '无锡市'
							}
						]
					},
					{
						value: 'zj',
						label: '浙江省',
						children: [{
								value: 'hz',
								label: '杭州市'
							},
							{
								value: 'nb',
								label: '宁波市'
							},
							{
								value: 'wz',
								label: '温州市'
							}
						]
					}
				],
				query: {
					condition: 'and',
					rules: [{
							field: 'FirstName',
							operator: 'equal',
							value: 'Nancy',
							type: 'string'
						},
						{
							condition: 'and',
							rules: [{
								field: 'Country',
								operator: 'equal',
								value: 'USA',
								type: 'string'
							}]
						}
					]
				}
			}
		},
		computed: {
			formattedQuery() {
				return JSON.stringify(this.query, null, 2)
			}
		},
		methods: {
			handleChange(newQuery) {
				console.log('Query changed:', newQuery)
			},
			handleCascaderChange(valueArr, scope) {
				const result = []
				let current = this.options
				valueArr.forEach(value => {
					const node = current.find(item => item.value === value)
					if (node) {
						result.push({
							value: node.value,
							label: node.label,
						})
						current = node.children || []
					}
				})
				const last = result.pop();
				scope.field = last.value;
				scope.label = last.label;
			}
		}
	}
</script>

<style>
	.container {
		max-width: 800px;
		margin: 20px auto;
		padding: 20px;
	}

	.output {
		margin-top: 20px;
		padding: 10px;
		background: #f5f7fa;
		border-radius: 4px;
		white-space: pre-wrap;
	}
</style>
